using UnityEngine;
using System.Collections;

public class CharacterMovement : MonoBehaviour 
{
	
	public float speed;
	public float maxVelocity;
	
	void Start()
	{
		if(rigidbody.drag != 3)
		{
			rigidbody.drag = 3;
		}
		
		this.speed = PlayerPrefs.GetFloat("SpeedChar",400);
		
		#if UNITY_ANDROID
		this.speed = 900;
		#endif
	}
	void Update () 
	{
        if (Input.GetKeyDown(KeyCode.R) && Input.touchCount == 2)
        {
            Application.LoadLevel(Application.loadedLevelName);
        }

		transform.position = new Vector3(transform.position.x,transform.position.y,-1);
		#if UNITY_STANDALONE || UNITY_WEBPLAYER
		
		if(Input.GetAxis("Horizontal") != 0)
		{
			if(rigidbody.velocity.x < maxVelocity && rigidbody.velocity.x > -maxVelocity)
			{
				rigidbody.AddForce((Input.GetAxis("Horizontal")*Vector3.right)*(speed*Time.deltaTime));
			}
		}
		
		if(Input.GetAxis("Vertical") != 0)
		{
			if(rigidbody.velocity.y < maxVelocity && rigidbody.velocity.y > -maxVelocity)
			{
				rigidbody.AddForce((Input.GetAxis("Vertical")*Vector3.up)*(speed*Time.deltaTime));
			}
		}

		#endif
	
		#if UNITY_ANDROID
	    Vector3 dir = Vector3.zero;
        dir.x = -Input.acceleration.y;
        dir.z = Input.acceleration.x;
        
        if (dir.sqrMagnitude > 1)
            dir.Normalize();

		if(dir.x != 0)
		{
			if(rigidbody.velocity.x < maxVelocity && rigidbody.velocity.x > -maxVelocity)
			{
				rigidbody.AddForce((dir.z)*Vector3.right*(speed*Time.deltaTime));
			}
		}

		if(dir.z != 0)
		{
			if(rigidbody.velocity.y < maxVelocity && rigidbody.velocity.y > -maxVelocity)
			{
				rigidbody.AddForce(-dir.x*Vector3.up*(speed*Time.deltaTime));
			}
		}
		#endif
	}
	
}

